package node

import (
	"context"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/apimachinery/pkg/util/json"
	"kubeimooc/global"
	node_req "kubeimooc/model/node/request"
	node_res "kubeimooc/model/node/response"
	"strings"
)

type NodeService struct {
}

/*
*
更新污点
*/
func (ns *NodeService) UpdateNodeTaint(updateTaint node_req.UpdatedTaint) error {
	patchData := map[string]any{
		"spec": map[string]any{
			"taints": updateTaint.Taints,
		},
	}
	patchDataBytes, _ := json.Marshal(patchData)
	_, err := global.KubeConfigSet.CoreV1().Nodes().Patch(
		context.TODO(),
		updateTaint.Name,
		types.StrategicMergePatchType,
		patchDataBytes,
		metav1.PatchOptions{},
	)
	return err
}

/*
*
更新node的标签
*/
func (ns *NodeService) UpdateNodeLabel(updatedLabel node_req.UpdatedLabel) error {
	labelMap := make(map[string]string, 0)
	for _, label := range updatedLabel.Labels {
		labelMap[label.Key] = label.Value
	}
	labelMap["$patch"] = "replace"
	patchData := map[string]any{
		"metadata": map[string]any{
			"labels": labelMap,
		},
	}
	patchDataBytes, _ := json.Marshal(patchData)
	_, err := global.KubeConfigSet.CoreV1().Nodes().Patch(
		context.TODO(),
		updatedLabel.Name,
		types.StrategicMergePatchType,
		patchDataBytes,
		metav1.PatchOptions{},
	)
	return err
}

/*
*
获取node的列表
*/
func (ns *NodeService) GetNodeList(keyword string) ([]node_res.Node, error) {
	//返回*v1.NodeList
	list, err := global.KubeConfigSet.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		return nil, err
	}
	nodesList := make([]node_res.Node, 0)
	for _, item := range list.Items {
		if strings.Contains(item.Name, keyword) {
			resItem := nodeConvert.GetNodeResItem(item)
			nodesList = append(nodesList, resItem)
		}
	}
	return nodesList, nil
}

/*
*
获取node详情
*/
func (ns NodeService) GetNodeDetail(nodeName string) (*node_res.Node, error) {
	//nodeK8s为指针的类型
	nodeK8s, err := global.KubeConfigSet.CoreV1().Nodes().Get(context.TODO(), nodeName, metav1.GetOptions{})
	if err != nil {
		return nil, err
	}
	detail := nodeConvert.GetNodeDetail(*nodeK8s)
	return &detail, nil
}
